package com.weixing.mall.provider.controller.front;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.DatePattern;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoRepeatSubmit;
import com.weixing.mall.core.annotation.RequestLimiter;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.MemAuth;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.model.vo.AgentRpcVo;
import com.weixing.mall.provider.api.service.AgentServiceRpc;
import com.weixing.mall.provider.manager.AgentManager;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.dto.AgentPlaceOrderDto;
import com.weixing.mall.provider.model.dto.OrderAuditDto;
import com.weixing.mall.provider.model.enums.*;
import com.weixing.mall.provider.model.query.AfterSaleQuery;
import com.weixing.mall.provider.model.query.AgentAuditHisQuery;
import com.weixing.mall.provider.model.query.AgentOrderQuery;
import com.weixing.mall.provider.model.query.ProductIdQuery;
import com.weixing.mall.provider.model.query.agent.AgentOrderStatisticQuery;
import com.weixing.mall.provider.model.vo.*;
import com.weixing.mall.provider.model.vo.agent.*;
import com.weixing.mall.provider.model.vo.cliam.OrderCliamResultVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.util.AgentOrderUtil;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 移动端-代理订单操作API
 *
 * @author siashan
 * @since v1.0
 **/
@Validated
@RestController
@RequestMapping("front/order/agent")
public class FrontAgentController extends BaseController {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderTradeService orderTradeService;
    @Autowired
    private IOrderOperationService orderOperationService;
    @Autowired
    private AgentManager agentManager;
    @Autowired
    private IAgentOrderService agentOrderService;
    @Autowired
    private IOrderAgentService orderAgentService;
    @Autowired
    private AgentServiceRpc agentServiceRpc;


    /**
     * 代理商下单
     *
     * @param dto  下单参数
     * @return 下单结果
     */
    @RequestLimiter(QPS = 5D, timeout = 2000, timeunit = TimeUnit.MILLISECONDS, msg = "亲，服务器快被挤爆了，请稍后再试！")
    @PostMapping("place")
    public Result place(@RequestBody AgentPlaceOrderDto dto) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        Result<AgentRpcVo> result1 = agentManager.checkAgent(abid, dto.getAgentId());
        if (!result1.isSuccess()) {
            return result1;
        }
        Result result = orderTradeService.preOrderOfAgent(dto, result1.getData());
        return result;
    }


    /**
     * 订单搜索
     *
     * @param query 查询参数
     * @return 订单分页数据
     */
    @GetMapping("search")
    public Result<IPage<FrontAgentOrderVo>> orderSeach(AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        query.setAgentIdForQueryAll(null == query.getSelectedAgentId() ? abid : query.getSelectedAgentId());
        IPage<FrontAgentOrderVo> records = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, abid);
        return ResultUtil.success(records);
    }


    /**
     * 代理商全部订单
     *
     * @apiNote 查询范围：自己的单子 + 团队的单子.查询条件传递agentIdForQueryAll字段
     *
     * @param query 查询条件
     * @return 查询结果
     */
    @GetMapping("allList")
    public Result<IPage<FrontAgentOrderVo>> alllist(AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
//        query.setAgentIdForQueryAll(null == query.getSelectedAgentId() ? abid : query.getSelectedAgentId());
        AgentRpcVo agentRpcVo = agentManager.loadAgentRpcVo(null == query.getSelectedAgentId() ? abid : query.getSelectedAgentId());
        AgentOrderUtil.wripeQuery(query,agentRpcVo);
        query.setIsPay(WhetherEnum.YES);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, abid);
        return ResultUtil.success(record);
    }


    /**
     * 代理订单列表-个人订单
     *
     * @apiNote 只包含个人的订单, 查询条件传递agentId字段
     *
     * @param query 查询条件
     * @return 查询结果
     */
    @GetMapping("persional")
    public Result<IPage<FrontAgentOrderVo>> selectFrontAgentOrderPrivatelist(AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        // 个人订单需要排除该字段
        query.setAgentIdForQueryAll(null);
        query.setAgentId(abid);
        query.setIsPay(WhetherEnum.YES);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, abid);
        return ResultUtil.success(record);
    }


    /**
     * 代理订单列表--待审核订单
     *
     * @apiNote 查询条件不能够传递agentId字段，应该传递auditor字段
     *
     * @param query 查询条件
     * @return 查询结果
     */
    @GetMapping("toAudit")
    public Result<IPage<FrontAgentOrderVo>> toAuditlist(AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        query.setAuditor(abid);
        query.setIsPay(WhetherEnum.YES);
        query.setAuditDept(AuditDeptEnum.AGENT);
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.HAS_PAY.getValue());
        states.add(OrderStateEnum.AUDITING.getValue());
        query.setOrderStates(states);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, abid);
        return ResultUtil.success(record);
    }


    /**
     * 代理订单列表--已审核订单
     *
     * @apiNote 我审核过的单子, 查询条件传递 hasAuditAgentId字段
     * @param query 查询条件
     * @return 查询结果
     */
    @GetMapping("hasAudit")
    public Result<IPage<FrontAgentOrderVo>> hasAuditList(AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        query.setIsPay(WhetherEnum.YES);
        query.setHasAuditAgentId(abid);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, abid);
        return ResultUtil.success(record);
    }

    /**
     * 代理订单列表--已认领订单
     *
     * @apiNote 查询条件传递agentId 字段
     * @param query 查询条件
     * @return 查询结果
     */
    @GetMapping("cliamList")
    public Result<IPage<FrontAgentOrderVo>> claimlist(AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        query.setAgentId(abid);
        query.setIsPay(WhetherEnum.YES);
        query.setIsClaim(OrderIsClaimEnum.HAS_CLAIM);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, abid);
        return ResultUtil.success(record);
    }

    /**
     * 方法描述: 已拒绝订单
     *
     * @apiNote 只包含个人的订单, 查询条件传递agentId字段
     * @param query 查询条件
     * @return 查询结果
     */
    @GetMapping("rejectList")
    public Result<IPage<FrontAgentOrderVo>> rejectList(AgentOrderQuery query) {
        Long agentId = AuthUtil.getMemberExt().getAbid();
        query.setAgentId(agentId);
        query.setOrderStatus(OrderStateEnum.REJECT);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, agentId);
        return ResultUtil.success(record);
    }

// TODO  这两个接口合并到代理商订单列表里面

//    /**
//     * 方法描述: 秒杀活动订单
//     *
//     * 自己的单子 + 团队的单子
//     *
//     * 查询条件传递agentIdForQueryAll字段
//     *
//     */
//    @ApiOperation(value = "代理订单列表--已认领订单")
//    @GetMapping("seckilllist")
//    public Result<IPage<FrontAgentOrderVo>> secKilllist( AgentOrderQuery query) {
//        Long agentId = AuthUtil.getMemberExt().getAbid();
//        query.setAgentIdForQueryAll(agentId);
//        query.setIsPay(WhetherEnum.YES);
//        query.setOrderType(OrderTypeEnum.SECKILL);
//        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, agentId);
//        return ResultUtil.success(record);
//    }

//    /**
//     * 方法描述: 代理商活动订单
//     *
//     * 查询范围：自己的单子 + 团队的单子
//     *
//     * 查询条件传递agentIdForQueryAll字段
//     * @Author Small
//     * @param auth
//     * @Date 2020/5/19 20:40
//     * @return com.weixing.mall.base.wrapper.Result
//     */
//    @ApiOperation(value = "代理商活动订单")
//    @GetMapping("agentActlist")
//    public Result<IPage<FrontAgentOrderVo>> agentActlist(@MemInfo MemAuth auth,AgentOrderQuery query) {
//        //AgentOrderQuery query = new AgentOrderQuery();
//        query.setAgentIdForQueryAll(auth.getAbid());
//        query.setIsPay(WhetherEnum.YES);
//        query.setOrderType(OrderTypeEnum.AGENT);
//        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, auth.getAbid());
//        return ResultUtil.success(record);
//    }


    /**
     * 方法描述: 根据订单id查询详情
     *
     * @param id  订单id
     * @return 订单详情
     */
    @ApiOperation(value = "根据订单id查询详情")
    @GetMapping("orderDetail/{id}")
    public Result orderDetail(@PathVariable Long id) {
        Long agentId = AuthUtil.getMemberExt().getAbid();
        FrontAgentOrderDetilsVo vo = agentOrderService.selectFrontAgentOrderDetils(id, agentId);
        return ResultUtil.success(vo);
    }


    /**
     * 根据商品Id和商品的sku查询出货品的Id
     * @param productIdQuery  查询条件
     * @return 货品id
     */
    @GetMapping("frontProductId")
    public Result<Long> selectProductId(ProductIdQuery productIdQuery) {
        return ResultUtil.success(orderService.selectProductId(productIdQuery));
    }


    /**
     * 代理商订单审核
     *
     * @param orderAudit 订单审核dto
     * @return 审核结果
     */
    @PostMapping("audit")
    @NoRepeatSubmit
    public Result frontAgentAudit(@RequestBody OrderAuditDto orderAudit) {
        MemAuth auth = AuthUtil.getMemberExt();
        orderOperationService.agentAudit(orderAudit, auth.getAbid(), auth.getAbn());
        return ResultUtil.success();
    }

    /**
     * 代理商订单批量审核
     *
     * @param ids 订单id,多个英文逗号隔开
     * @return 审核结果
     */
    @PostMapping("audit/batch")
    @NoRepeatSubmit
    public Result batchAudit(String ids) {
        MemAuth auth = AuthUtil.getMemberExt();
        String[] arrayList = ids.split(",");
        List<OrderAuditDto> orderAuditDtoList = Lists.newArrayList();
        if (arrayList != null && arrayList.length > 0) {
            OrderAuditDto dto = null;
            for (String ss : arrayList) {
                dto = new OrderAuditDto();
                dto.setAuditState(AuditStateEnum.AGGREE);
                dto.setOrderId(Long.valueOf(ss));
                orderAuditDtoList.add(dto);
            }
        }
        if (CollUtil.isNotEmpty(orderAuditDtoList)) {
            for (OrderAuditDto dto : orderAuditDtoList) {
                orderOperationService.agentAudit(dto, auth.getAbid(), auth.getAbn());
            }
        }
        return ResultUtil.success();
    }

    /**
     * 代理商订单批量拒绝
     *
     * @param ids 订单id,多个英文逗号隔开
     * @return 审核结果
     */
    @PostMapping("reject/batch")
    @NoRepeatSubmit
    public Result batchReject(String ids) {
        MemAuth auth = AuthUtil.getMemberExt();
        String[] arrayList = ids.split(",");
        List<OrderAuditDto> orderAuditDtoList = Lists.newArrayList();
        if (arrayList != null && arrayList.length > 0) {
            OrderAuditDto dto = null;
            for (String ss : arrayList) {
                dto = new OrderAuditDto();
                dto.setAuditState(AuditStateEnum.REJECT);
                dto.setOrderId(Long.valueOf(ss));
                orderAuditDtoList.add(dto);
            }
        }
        if (CollUtil.isNotEmpty(orderAuditDtoList)) {
            for (OrderAuditDto dto : orderAuditDtoList) {
                orderOperationService.agentAudit(dto, auth.getAbid(), auth.getAbn());
            }
        }
        return ResultUtil.success();
    }


    /**
     * 代理商认领订单
     *
     * @apiNote 已废弃
     * @param orderIds  订单id列表
     * @return 认领结果
     */
    @PostMapping("claim")
    @Deprecated
    public Result claimOrder(String orderIds) {
        if (StrUtil.isEmpty(orderIds)) {
            return ResultUtil.error("参数有误");
        }
        String[] orderIdArray = orderIds.split(GlobalConstant.symbol.COMMA);
        if (orderIdArray == null) {
            return ResultUtil.error("参数有误");
        }
        List<String> idsStr = Arrays.asList(orderIdArray);
        List<Order> orders = (List<Order>) orderService.listByIds(idsStr);
        String errMsg = null;
        if (CollUtil.isNotEmpty(orders)) {
            for (Order order : orders) {
                if (0 != order.getAgentId() || null != order.getCustomerId()) {
                    errMsg = "部分订单已被认领，请重新选择";
                    break;
                }
            }
        }
        if (StringUtil.isNotEmpty(errMsg)) {
            return ResultUtil.error(errMsg);
        }
        agentOrderService.claimOrder(orders);
        return ResultUtil.success();
    }


    /**
     * 根据订单识别码查询可认领订单
     *
     * @apiNote 已废弃
     * @param orderSns   订单认领码列表，多个英文逗号隔开
     * @return 订单列表
     */
    @PostMapping("canClaimlist")
    @Deprecated
    public Result<List<FrontAgentCliamOrderVo>> canClaimlist(@RequestBody String orderSns) {
        return ResultUtil.success(agentOrderService.selectFrontAgentOrderCanClaimlist(orderSns));
    }

    /**
     * 根据订单识别码认领订单
     * TODO 待调试
     * @param orderSns  订单识别码，多个识别码英文逗号隔开
     * @return 可认领详情
     * @since v2.0.1
     */
    @ApiOperation(value = "根据订单识别码认领订单")
    @PostMapping("claimOrder")
    public Result<OrderCliamResultVo> claimOrderNew(@NotNull(message = "订单识别码不能为空") @RequestBody String orderSns) {
        return ResultUtil.success(agentOrderService.selectOrderCanClaimlist(orderSns.trim()));
    }


    /**
     * 方法描述: 订单列表页面统计请求
     *
     * @apiNote 已废弃
     * TODO V2.0之后废弃
     * @param type   订单类型
     *               1全部  2 已提交  3 待审核  4 已审核  5 代理活动  6 秒杀  7 已认领
     * @return 统计结果
     */
    @Deprecated
    @ApiOperation(value = "我的订单统计数据")
    @GetMapping("statistics/{type}")
    public Result selectFrontAgentOrderStatistics(@PathVariable Integer type) {
        return ResultUtil.success(agentOrderService.getFrontAgentOrderStatistics(AuthUtil.getMemberExt().getAbid(), type));
    }

    /**
     * 方法描述: 订单列表页面统计请求
     *
     * @param query  查询条件
     * @return 统计结果
     * @since V2.0.1
     */
    @ApiOperation(value = "我的订单统计数据")
    @PostMapping("statistics")
    public Result<AgentOrderStatisticVo> orderStatistics(@RequestBody AgentOrderStatisticQuery query) {
        return ResultUtil.success(agentOrderService.orderStatistics(query));
    }

    /**
     * 代理APP【销售报表】我的销售明细
     *
     * @param type own 个人；group 团队
     * @param query 查询参数
     * @return 销售明细
     */
    @PostMapping("sales/{type}")
    public Result<IPage<FrontAgentOrderVo>> salesDetail(@PathVariable String type, @RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        wrapSale(query);
        AgentOrderUtil.wrapSaleQuery(type, query, agentRpcVo);
        IPage<FrontAgentOrderVo> frontAgentOrderVoIPage = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, memAuth.getAbid());
        return ResultUtil.success(frontAgentOrderVoIPage);
    }

//    /**
//     * 代理APP【销售报表】 我的销售统计
//     *
//     * @apiNote 仅支持时间范围查询
//     * @param type own 个人；group 团队
//     * @return 销售统计
//     */
//    @PostMapping("sales/statistics/{type}")
//    public Result<AgentSaleStatisticVo> salesStatistics(@PathVariable String type, @RequestBody AgentStatisticQuery query) {
//        Long abid = AuthUtil.getMemberExt().getAbid();
//
//        query.setAuditStartTime(query.getStartTime());
//        query.setAuditEndTime(query.getEndTime());
//
//        query.setStartTime(null);
//        query.setEndTime(null);
//        AgentSaleStatisticVo relust = agentOrderService.getFrontAgentSalesStatistics(abid, type, query);
//        return ResultUtil.success(relust);
//    }

    /**
     * 代理APP【销售报表】 我的销售统计
     *
     * @apiNote 仅支持时间范围查询
     * @param type own 个人；group 团队
     * @return 销售统计
     */
    @PostMapping("sales/statistics/{type}")
    public Result<AgentSaleStatisticVo> salesStatistics(@PathVariable String type, @RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        wrapSale(query);
        AgentOrderUtil.wrapSaleQuery(type, query, agentRpcVo);
        AgentSaleStatisticVo relust = agentOrderService.getFrontAgentSalesStatistics(query);
        return ResultUtil.success(relust);
    }

    private void wrapSale(AgentOrderQuery query) {
        query.setAuditStatus(OrderAuditStateEnum.KEFU_AUDITING);
        query.setAuditStartTime(query.getStartTime());
        query.setAuditEndTime(query.getEndTime());
        query.setStartTime(null);
        query.setEndTime(null);
    }

    /**
     * 线上返利报表
     *
     * @apiNote 线上订单 & 正价订单 & 会员下单 & 客服审核通过 & 包含下级订单
     *
     * @param query 查询条件
     * @return 返利报表
     */
    @PostMapping("profitOrderDetail")
    public Result<IPage<FrontAgentOrderVo>> profitOrderDetail(@RequestBody AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        query.setAgentIdForQueryAll(abid);
        query.setOrderFrom(OrderFromEnum.MEMBER);
        query.setOrderType(OrderTypeEnum.NORMAL);
        query.setAuditStatus(OrderAuditStateEnum.KEFU_AUDITING);
        IPage<FrontAgentOrderVo> frontAgentOrderVoIPage = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, abid);
        return ResultUtil.success(frontAgentOrderVoIPage);
    }

    /**
     * 线上返利报表统计
     *
     * @apiNote 线上订单 & 正价订单 & 会员下单 & 客服审核通过 & 包含下级订单
     * @param query 查询条件
     * @return 统计信息
     */
    @PostMapping("profit/statistics")
    public Result<RebateStatisticVo> profitStatistics(@RequestBody AgentOrderQuery query) {
        Long abid = AuthUtil.getMemberExt().getAbid();
        RebateStatisticVo relust = agentOrderService.getFrontAgentprofitStatistics(abid, query);
        return ResultUtil.success(relust);
    }


    /**
     * 需上交金额页面
     *
     * @apiNote 上交人传递 selectedAgentId
     * @param query 查询条件
     * @return 订单列表
     */
    @PostMapping("upPay")
    public Result<IPage<FrontAgentOrderVo>> upPay(@RequestBody AgentOrderQuery query) {
        Long agentId = AuthUtil.getMemberExt().getAbid();
        query.setAuditor(agentId);
        query.setIsPay(WhetherEnum.YES);
        query.setAuditDept(AuditDeptEnum.AGENT);
        query.setOrderFrom(OrderFromEnum.AGENT);
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.HAS_PAY.getValue());
        states.add(OrderStateEnum.AUDITING.getValue());
        query.setOrderStates(states);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectUpPayOrderList(initMpPage(), query, agentId);
        return ResultUtil.success(record);
    }


    /**
     * 需上交金额统计
     *
     * @apiNote 上交人传递 selectedAgentId
     * @param query 查询条件
     * @return 统计信息
     */
    @PostMapping("upPay/statistics")
    public Result<UpPayStatisticVo> upPayStatistics(@RequestBody AgentOrderQuery query) {
        Long agentId = AuthUtil.getMemberExt().getAbid();
        query.setAgentId(agentId);
        UpPayStatisticVo result = orderAgentService.upPayStatistics(query);
        return ResultUtil.success(result);
    }


    /**
     * 异常订单列表
     *
     * @param type 异常类型
     * @return 订单列表
     */
    @GetMapping("abnormalOrder/{type}")
    public Result<IPage<FrontAgentOrderVo>> abnormalOrder(@PathVariable AfterSalesTypeEnum type) {
        Long agentId = AuthUtil.getMemberExt().getAbid();
        AfterSaleQuery query = new AfterSaleQuery();
        query.setAgentId(agentId);
        query.setAfterSaleType(type);
        String todayTimeFmt = DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN);
        query.setStartTime(todayTimeFmt);
        query.setEndTime(todayTimeFmt);
        IPage<FrontAgentOrderVo> iPage = agentOrderService.selectAfterSaleOrderList(initMPage(), query);
        return ResultUtil.success(iPage);
    }


    /**
     * 退货订单报表-明细
     *
     * @apiNote 客服审核通过 & 包含下级
     * @param query 查询条件
     * @return 订单列表
     */
    @PostMapping("returnOrdersReport")
    public Result<IPage<FrontAgentOrderVo>> returnOrdersReport(@RequestBody AfterSaleQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setAfterSaleType(AfterSalesTypeEnum.RETURN_GOODS);
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        IPage<FrontAgentOrderVo> iPage = agentOrderService.selectAfterSaleOrderList(initMPage(), query);
        return ResultUtil.success(iPage);
    }


    /**
     * 退货订单报表-统计
     *
     * @apiNote 客服审核通过 & 包含下级
     * @param query 查询条件
     * @return 统计信息
     */
    @PostMapping("returnOrder/statistics")
    public Result<AbnormalOrderStatisticVo> returnOrderStatistics(@RequestBody AfterSaleQuery query) {
        Long agentId = AuthUtil.getMemberExt().getAbid();
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setAfterSaleType(AfterSalesTypeEnum.RETURN_GOODS);
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        AbnormalOrderStatisticVo result = agentOrderService.selectReturnStatistics(agentId, query);
        return ResultUtil.success(result);
    }

    /**
     * 换货订单报表-明细
     *
     * @param query 查询条件
     * @return 订单列表
     */
    @PostMapping("exchangeOrdersReport")
    public Result<IPage<FrontAgentOrderVo>> exchangeOrdersReport(@RequestBody AfterSaleQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setAfterSaleType(AfterSalesTypeEnum.EXCHANE_GOODS);
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        IPage<FrontAgentOrderVo> iPage = agentOrderService.selectAfterSaleOrderList(initMPage(), query);
        return ResultUtil.success(iPage);
    }

    /**
     * 换货订单报表-统计
     *
     * @param query 查询条件
     * @return 统计信息
     */
    @PostMapping("exchangeOrders/statistics")
    public Result<AbnormalOrderStatisticVo> exchangeOrdersStatistics(@RequestBody AfterSaleQuery query) {
        Long agentId = AuthUtil.getMemberExt().getAbid();
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setAfterSaleType(AfterSalesTypeEnum.EXCHANE_GOODS);
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        AbnormalOrderStatisticVo result = agentOrderService.selectExchangeStatistics(agentId, query);
        return ResultUtil.success(result);
    }


    /**
     * 断货订单报表-明细
     *
     * @apiNote 客服审核通过 & 包含下级
     * @param query 查询条件
     * @return 订单列表
     */
    @PostMapping("outOfStockReport")
    public Result<IPage<FrontAgentOrderVo>> outOfStockReport(@RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Long agentId = memAuth.getAbid();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setItemStatus(ProductStatusEnum.STATUS6.getValue());
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        IPage<FrontAgentOrderVo> iPage = agentOrderService.selectAgentOrderListOfPage(initMPage(), query, agentId);
        return ResultUtil.success(iPage);
    }

    /**
     * 断货订单报表-统计
     *
     * @apiNote 客服审核通过 & 包含下级
     * @param query 查询条件
     * @return 统计信息
     */
    @PostMapping("outOfStockReport/statistics")
    public Result<AbnormalOrderStatisticVo> outOfStockReportStatistics(@RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Long agentId = memAuth.getAbid();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setItemStatus(ProductStatusEnum.STATUS6.getValue());
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        AbnormalOrderStatisticVo result = agentOrderService.outOfStockReportStatistics(agentId, query);
        return ResultUtil.success(result);
    }


    /**
     * 取消订单列表
     *
     * @param query  查询条件
     * @return 订单列表
     */
    @PostMapping("canceledlist")
    public Result<IPage<FrontAgentOrderVo>> canceledlist(@RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Long agentId = memAuth.getAbid();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setItemStatus(ProductStatusEnum.STATUS7.getValue());
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, agentId);
        return ResultUtil.success(record);
    }


    /**
     * 取消订单列表-统计
     *
     * @apiNote 仅支持时间范围查询
     * @param query 查询条件
     * @return 统计信息
     */
    @PostMapping("canceled/statistics")
    public Result<AbnormalOrderStatisticVo> canceledStatistics(@RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setItemStatus(ProductStatusEnum.STATUS7.getValue());
        AgentOrderUtil.wripeQuery(query, agentRpcVo);
        AbnormalOrderStatisticVo result = agentOrderService.canceledStatistics(query);
        return ResultUtil.success(result);
    }


    /**
     * 业绩报表
     *
     * @param type 订单类型
     * @param query 查询条件
     * @return 报表明细
     */
    @PostMapping("achievement/{type}")
    public Result<IPage<SalesAchiVo>> achievement(@PathVariable OrderTypeEnum type, @RequestBody AgentOrderQuery query) {
        query.setAuditStatus(OrderAuditStateEnum.KEFU_AUDITING);
        IPage<SalesAchiVo> page = agentOrderService.achievement(initMpPage(), type, query);
        return ResultUtil.success(page);
    }


    /**
     * 我的业绩明细
     *
     * @param type 团队/个人  own 个人 ； group 团队
     * @param query 查询条件
     * @return 订单列表
     */
    @PostMapping("achievement/detail/{type}")
    public Result<IPage<FrontAgentOrderVo>> achievementDetail(@PathVariable String type, @RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        Long agentId = memAuth.getAbid();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setAuditStatus(OrderAuditStateEnum.KEFU_AUDITING);
        AgentOrderUtil.wrapSaleQuery(type, query, agentRpcVo);
        IPage<FrontAgentOrderVo> frontAgentOrderVoIPage = agentOrderService.selectAgentOrderListOfPage(initMpPage(), query, agentId);
        return ResultUtil.success(frontAgentOrderVoIPage);
    }

    /**
     * 我的业绩统计
     *
     * @param type 团队/个人  own 个人 ； group 团队
     * @param query 查询条件
     * @return com.weixing.mall.base.wrapper.Result
     */
    @PostMapping("achievement/statistics/{type}")
    public Result<AgentSaleStatisticVo> achievementStatistics(@PathVariable String type, @RequestBody AgentOrderQuery query) {
        MemAuth memAuth = AuthUtil.getMemberExt();
        AgentRpcVo agentRpcVo = agentManager.loadAgent(query.getSelectedAgentId(), memAuth);
        query.setAuditStatus(OrderAuditStateEnum.KEFU_AUDITING);
        AgentOrderUtil.wrapSaleQuery(type, query, agentRpcVo);
        AgentSaleStatisticVo relust = agentOrderService.getFrontAchievementStatistics(query);
        return ResultUtil.success(relust);
    }


    /**
     * 修改订单(颜色尺码)
     * @param orderId 订单id
     * @param itemId  商品id
     * @return 修改结果
     */
    @PostMapping("updateOrderGoods/{orderId}/{itemId}")
    public Result updateOrderGoods(@PathVariable Long orderId, @PathVariable Long itemId) {
        long agentId = AuthUtil.getMemberExt().getAbid();
        Order order = orderService.getById(orderId);
        if (OrderFromEnum.AGENT.getValue().equals(order.getOrderFrom()) && OrderTypeEnum.NORMAL.getValue().equals(order.getOrderType())) {
            if (agentId == order.getAgentId().longValue()) {
                if (!OrderAuditStateEnum.AGENT_WAIT_AUDIT.getValue().equals(order.getAuditStatus())) {
                    return ResultUtil.error("只有待审核订单才能修改");
                }
            } else {
                return ResultUtil.error("只能修改您自己下的订单");
            }
        } else {
            return ResultUtil.error("非代理正价订单禁止修改");
        }
        orderTradeService.updateOrderGoods(orderId, itemId);
        return ResultUtil.success();
    }


    /**
     * 删除订单
     * @param orderId 订单id
     * @return 删除结果
     */
    @ApiOperation(value = "")
    @PostMapping("del/{orderId}")
    public Result del(@PathVariable Long orderId) {
        long agentId = AuthUtil.getMemberExt().getAbid();
        Order order = orderService.getById(orderId);
        // 1、只能删除自己下的单（包括自己直接会员的单）
        if (agentId != order.getAgentId().longValue()) {
            return ResultUtil.error("只能删除您自己下的订单");
        }
        // 2、只有待审核的单才能删除
        if (!OrderAuditStateEnum.AGENT_WAIT_AUDIT.getValue().equals(order.getAuditStatus())) {
            return ResultUtil.error("只有待审核订单才能删除");
        }
        // 3、
        if (!OrderFromEnum.AGENT.getValue().equals(order.getOrderFrom())) {
            return ResultUtil.error("非代理活动单不可以删除");
        }
        order.setIsDel(WhetherEnum.YES.getValue());
        orderService.updateById(order);
        return ResultUtil.success();
    }


    /**
     * 审核历史
     * @param query 查询条件
     * @return 审核历史
     */
    @GetMapping("auditHis")
    public Result<IPage<KefuAuditOrderVo>> auditHis(AgentAuditHisQuery query) {
        long agentId = AuthUtil.getMemberExt().getAbid();
        query.setAgentId(agentId);
        IPage<KefuAuditOrderVo> page = agentOrderService.selectAuditHisList(agentId, query, initMpPage());
        return ResultUtil.success(page);
    }


    /**
     * 审核历史统计
     * @param query 查询条件
     * @return 审核历史
     */
    @GetMapping("auditHis/statistics")
    public Result<AuditHisCntVo> auditHisstatistics(AgentAuditHisQuery query) {
        long agentId = AuthUtil.getMemberExt().getAbid();
        query.setAgentId(agentId);
        AuditHisCntVo auditHisCntVo = agentOrderService.auditHisListSta(query);
        return ResultUtil.success(auditHisCntVo);
    }

    private Result<AgentRpcVo> getAgentRpcVoResult(Long agentId) {
        Result<AgentRpcVo> agentRpcVoResult = agentServiceRpc.selectByAgentId(agentId);
        if (!agentRpcVoResult.isSuccess()) {
            throw new BusinessException("代理商服务暂时不可用");
        }
        return agentRpcVoResult;
    }

}
